import { Component, OnInit } from '@angular/core';
import {DeptService} from "../../dept/dept.service";
import {NzMessageService, NzModalSubject} from "ng-zorro-antd";
import {UserService} from "../user.service";
import {RoleService} from "../../role/role.service";

class User {
    id;
    name;
    account;
    deptid;
    roleid;
    sex;
    phone;
    email;
    enable;
    remark;
}

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styleUrls: ['./user-edit.component.scss']
})
export class UserEditComponent implements OnInit {

    i;

    _item: User = new User();
    _options = null;
    _loaded = false;
    _value: any[] = [];

    _options2 = [];
    _selectedOption2;

    _changeValue(value) {
        this._item.deptid = this._value[this._value.length - 1];
        this._item.roleid = null;
        this._loadRoleList();
    }

    _addIsLeafField(list) {
        list.forEach((val, idx, array) => {
            if (val.children) {
                this._addIsLeafField(val.children);
            } else {
                val.isLeaf = true;
            }
        });
    }

    _setParent(cur) {
        if (cur.id !== 0) {
            this.service.getList(cur.deptid).subscribe(data => {
                this._value = data;
            });
        }
    }

    save() {
        this.srv.save(this._item).subscribe(() => {
            this.nzMessage.success('保存成功');
            this.subject.next(true);
            this.close();
        });
    }

    close() {
        this.subject.destroy();
    }

    constructor(private subject: NzModalSubject,
                private nzMessage: NzMessageService,
                private service: DeptService,
                private roleSrv: RoleService,
                private srv: UserService) {
    }

    ngOnInit() {
        this._setParent(this.i);
        this._item.id = this.i.id;
        if (this._item.id > 0) {
            this._item.name = this.i.name;
            this._item.account = this.i.account;
            this._item.deptid = this.i.deptid;
            this._item.roleid = this.i.roleid;
            this._item.sex = this.i.sex;
            this._item.phone = this.i.phone;
            this._item.email = this.i.email;
            this._item.enable = this.i.enable;
            this._item.remark = this.i.remark;
        } else {
            this._item.enable = false;
        }
        this.service.getTree().subscribe(data => {
            this._addIsLeafField(data);
            this._options = data;
            this._loaded = true;
        });
        this._loadRoleList();
    }

    _loadRoleList() {
        this.roleSrv.get(this._item.deptid).subscribe(data => {
            this._options2 = data;
        });
    }

}
